const router=require('koa-router')();
const crypto=require('crypto');
const config=require('../config/config');
const checkNotLogin=require('../middlewares/checkNotLogin');
const redis=require('../models/redis.server.model');
const {User}=require('../models/index');

//activate
router.get('/:id',checkNotLogin(),async ctx=>{
    let id=ctx.params.id,activatedUser=await redis.getActivatedById(id);

    /*ioredis.hgetall()查询不存在的Key时，会返回空对象*/
    if(!activatedUser || !activatedUser.name)return ctx.flash={error:'已经超过激活有效期'},ctx.redirect('/reg');

    await ctx.render('activate',{
        title:'激活',
        activatedUser,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

router.post('/:id',checkNotLogin(),async ctx=>{
    let id=ctx.params.id,user=await redis.getActivatedById(id);
    if(!user || !user.name)return ctx.flash={error:'已经超过激活有效期'},ctx.redirect('/reg');

    user.regTime=new Date(user.regTimeStr);
    user.token=crypto.createHash('md5').update([config.secret,user.name,user.email].join('&')).digest('hex');

    await new User(user).save();
    await redis.delUser(user);

    ctx.flash={success:'已成功激活，请登录'};
    ctx.redirect('/login');
});

module.exports=router;